package com.yufubao.service.service.applet.product.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yufubao.framework.constant.SupplierInfoConstant;
import com.yufubao.framework.constant.UserTypeConstant;
import com.yufubao.framework.exception.BaseException;
import com.yufubao.framework.interceptor.AppletInterceptor;
import com.yufubao.framework.interceptor.local.LoginUserLoc;
import com.yufubao.framework.result.CheckSupplier;
import com.yufubao.framework.result.PageUtils;
import com.yufubao.framework.result.ResponseResult;
import com.yufubao.framework.util.CopyBean;
import com.yufubao.framework.util.MyCollUtil;
import com.yufubao.framework.util.page.Query;
import com.yufubao.model.pojo.applet.authorization.UserEntity;
import com.yufubao.model.pojo.applet.product.SpuInfoEntity;
import com.yufubao.model.pojo.applet.product.SupplierInfoEntity;
import com.yufubao.model.pojo.popularize.authorization.BeesInfoEntity;
import com.yufubao.model.vo.management.check.SearchAllStatusInfoVo;
import com.yufubao.model.vo.management.sys.SupplierInfoVo;
import com.yufubao.service.mapper.applet.product.SpuInfoDao;
import com.yufubao.service.mapper.applet.product.SupplierInfoDao;
import com.yufubao.service.service.applet.authorization.UserService;
import com.yufubao.service.service.applet.product.SupplierInfoService;
import com.yufubao.service.service.common.ElasticsearchUtilService;
import com.yufubao.service.service.common.util.ServiceUtil;
import com.yufubao.service.service.popularize.authorization.BeesInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.yufubao.framework.constant.ManagerStatus.ADMIN;
import static com.yufubao.framework.constant.SupplierInfoConstant.WAIT;
import static com.yufubao.framework.enums.CommonExceptionEnum.DQSHCZSP;
import static com.yufubao.framework.enums.CommonExceptionEnum.NOT_FOUND;
import static com.yufubao.framework.util.MapParamsUtil.getKey;
import static com.yufubao.framework.util.MapParamsUtil.getStatus;
import static com.yufubao.framework.util.SecurityUtils.checkUserLoc;


@Service("supplierInfoService")
public class SupplierInfoServiceImpl extends ServiceImpl<SupplierInfoDao, SupplierInfoEntity> implements SupplierInfoService {

    @Autowired
    private ElasticsearchUtilService elasticsearchUtilService;

    @Autowired
    private SpuInfoDao spuInfoDao;

    @Autowired
    private UserService userService;

    @Autowired
    private BeesInfoService beesInfoService;

    @Autowired
    private ServiceUtil serviceUtil;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SupplierInfoEntity> page = this.page(
                new Query<SupplierInfoEntity>().getPage(params),
                new QueryWrapper<SupplierInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * @param supplierInfoId
     * @return com.yufubao.framework.enums.CommonExceptionEnum
     * @description 商户修改营业状态
     * @author zhangyiheng
     * @date 2024/9/3 22:07
     */
    @Override
    @Transactional
    public ResponseResult updateHolidayState(Long supplierInfoId, String holidayState) {

        LoginUserLoc loginUserLoc = checkUserLoc(AppletInterceptor.APPLETTHREADLOCAL);

        //判断当前线程
        CheckSupplier.checkSupplierInfo(loginUserLoc, supplierInfoId);

        this.update(Wrappers.<SupplierInfoEntity>lambdaUpdate()
                .eq(SupplierInfoEntity::getSupplierInfoId, supplierInfoId)
                .set(SupplierInfoEntity::getIsHoliday, holidayState));

        //修改es索引数据
        //根据 id 来修改
        return elasticsearchUtilService.updateEsRst(supplierInfoId, holidayState, "isHoliday");
    }


    /**
     * @param supplierInfoId
     * @param shopFrontUrl
     * @return com.yufubao.framework.result.ResponseResult
     * @description 商户修改店基本信息（门照/封面）
     * @author zhangyiheng
     * @date 2024/9/5 10:06
     */
    @Override
    @Transactional
    public ResponseResult updateCover(Long supplierInfoId, String shopFrontUrl) {
        LoginUserLoc loginUserLoc = checkUserLoc(AppletInterceptor.APPLETTHREADLOCAL);

        //判断当前线程
        CheckSupplier.checkSupplierInfo(loginUserLoc, supplierInfoId);

        this.update(Wrappers.<SupplierInfoEntity>lambdaUpdate()
                .eq(SupplierInfoEntity::getSupplierInfoId, supplierInfoId)
                .set(SupplierInfoEntity::getShopFrontUrl, shopFrontUrl));

        //修改es索引数据
        //根据 id 来修改
        return elasticsearchUtilService.updateEsRst(supplierInfoId, shopFrontUrl, "shopFrontUrl");
    }

    /**
     * @param supplierInfoId
     * @return com.yufubao.framework.result.ResponseResult
     * @description 商户删除店信息
     * @author zhangyiheng
     * @date 2024/9/5 10:19
     */
    @Override
    @Transactional
    public ResponseResult deleteInfo(Long supplierInfoId) {
        LoginUserLoc loginUserLoc = checkUserLoc(AppletInterceptor.APPLETTHREADLOCAL);

        //判断当前线程商户权限
        CheckSupplier.checkSupplierInfo(loginUserLoc, supplierInfoId);

        //查询当前商户是否存在spu信息
        List<SpuInfoEntity> list = spuInfoDao.selectList(Wrappers.<SpuInfoEntity>lambdaQuery()
                .eq(SpuInfoEntity::getSupplierInfoId, supplierInfoId));
        if (MyCollUtil.isNotEmpty(list)) {
            throw new BaseException(DQSHCZSP);
        }


        //TODO 商家提现等？


        //删除商户信息
        this.removeById(supplierInfoId);

        //查询当前商家下是否存在其他商户信息
        long count = this.count(Wrappers.<SupplierInfoEntity>lambdaQuery()
                .eq(SupplierInfoEntity::getUserId, loginUserLoc.getUserId()));
        if (count == 0) {
            //商家转为用户
            userService.update(Wrappers.<UserEntity>lambdaUpdate()
                    .set(UserEntity::getUserType, UserTypeConstant.USER_TYPE_ORDINARY)
                    .eq(UserEntity::getUserId, loginUserLoc.getUserId()));
        }

        //删除es当前商户信息
        elasticsearchUtilService.supplierInfoDel(supplierInfoId);

        return ResponseResult.ok();
    }


    @Override
    public PageUtils searchAllStatusInfo(Map<String, Object> params) {

        //法人/店铺名称/手机号码
        String key = getKey(params);
        //0待审核1审核通过2审核未通过
        String status = getStatus(params);

        LambdaQueryWrapper<SupplierInfoEntity> wrapper = Wrappers.<SupplierInfoEntity>lambdaQuery()
                .eq(SupplierInfoEntity::getStatus, status);

        if (StrUtil.isNotBlank(key)) {
            wrapper.like(StrUtil.isNotBlank(key), SupplierInfoEntity::getLegalPerson, key)
                    .or(wq -> wq.like(StrUtil.isNotBlank(key), SupplierInfoEntity::getStoreName, key)
                            .or().eq(StrUtil.isNotBlank(key), SupplierInfoEntity::getMobile, key));
        }

        IPage<SupplierInfoEntity> page = this.page(
                new Query<SupplierInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public SearchAllStatusInfoVo searchWaitPass(Long supplierInfoId) {

        SupplierInfoEntity info = this.getOne(Wrappers.<SupplierInfoEntity>lambdaQuery()
                .eq(SupplierInfoEntity::getSupplierInfoId, supplierInfoId)
                .eq(SupplierInfoEntity::getStatus, WAIT));
        if (!Objects.isNull(info)) {
            return CopyBean.copyBean(info, SearchAllStatusInfoVo.class);
        }
        return null;
    }

    /**
     * @param params
     * @return com.yufubao.framework.result.PageUtils
     * @description 查询当前人员下小蜜蜂的商家信息
     * @author zhangyiheng
     * @date 2024/9/18 15:22
     */
    @Override
    public PageUtils pageList(Map<String, Object> params) {
        long managerId = StpUtil.getLoginIdAsLong();

        //店铺名称/法人/手机号码 只查询审核通过的
        String key = getKey(params);


        //查询当前人员代理的小蜜蜂集合
        List<BeesInfoEntity> beeses = beesInfoService.list(Wrappers.<BeesInfoEntity>lambdaQuery()
                .eq(BeesInfoEntity::getManagerId, managerId));

        if (!MyCollUtil.isNotEmpty(beeses)) {
            throw new BaseException(NOT_FOUND);
        }

        //获取小蜜蜂id集合查询商家推荐人
        List<Long> beesIds = beeses.stream().map(BeesInfoEntity::getBeesId).collect(Collectors.toList());

        LambdaQueryWrapper<SupplierInfoEntity> wrapper = Wrappers.<SupplierInfoEntity>lambdaQuery()
                .eq(SupplierInfoEntity::getStatus, SupplierInfoConstant.SUCCESS);

        if (StrUtil.isNotBlank(key)) {
            wrapper.like(StrUtil.isNotBlank(key), SupplierInfoEntity::getLegalPerson, key)
                    .or(wq -> wq.like(StrUtil.isNotBlank(key), SupplierInfoEntity::getStoreName, key)
                            .eq(StrUtil.isNotBlank(key), SupplierInfoEntity::getMobile, key));
        }

        //admin查询所有
        if (!Objects.equals(managerId, ADMIN)) {
            wrapper.in(SupplierInfoEntity::getBeesId, beesIds);
        }

        IPage<SupplierInfoEntity> page = this.page(
                new Query<SupplierInfoEntity>().getPage(params),
                wrapper
        );

        List<SupplierInfoEntity> records = page.getRecords();


        if (MyCollUtil.isNotEmpty(records)) {

            List<SupplierInfoVo> vos = new ArrayList<>();
            records.forEach(po -> {
                SupplierInfoVo vo = CopyBean.copyBean(po, SupplierInfoVo.class);
                Map<String, String> map = serviceUtil.getName(po);
                vo.setUserName(map.get("userName"));
                vo.setCategoryName(map.get("categoryName"));
                vo.setBeesName(map.get("beesName"));

                vos.add(vo);
            });
            IPage<SupplierInfoVo> pageVo = new Page<>();
            pageVo.setTotal(page.getTotal());
            pageVo.setPages(page.getPages());
            pageVo.setCurrent(page.getCurrent());
            pageVo.setRecords(vos);
            pageVo.setSize(page.getSize());
            return new PageUtils(pageVo);
        }

        return null;
    }


}